<template>
  <div class="app-container">
    <EsHeader title="购物车案例"></EsHeader>
    <EsGoodsVue
      v-for="item in goodslist"
      :key="item.id"
      :id="item.id"
      :thumb="item.goods_img"
      :title="item.goods_name"
      :price="item.goods_price"
      :checked="item.goods_state"
      :count="item.goods_count"
      @checkedChange="getChecked"
    ></EsGoodsVue>
    <EsFooter
      :amount="amount"
      :total="total"
      :isfull="isfull"
      @fullChange="fullChange"
    ></EsFooter>
  </div>
</template>

<script>
import EsHeader from './components/es-header/EsHeader.vue'
import EsFooter from './components/es-footer/EsFooter.vue'
import EsGoodsVue from './components/es-goods/EsGoods.vue'
import bus from './eventBus.js'

export default {
  name: 'MyApp',
  components: {
    EsHeader,
    EsFooter,
    EsGoodsVue
  },
  data() {
    return {
      goodslist: [],
      isfull: false
    }
  },
  methods: {
    async getGoodList() {
      const { data: res } = await this.$http.get('/api/cart')
      console.log(res)
      if (res.status !== 200) return alert('数据请求失败!')
      else this.goodslist = res.list
    },
    getChecked(obj) {
      this.goodslist[obj.id - 1].goods_state = obj.value
      if (this.goodslist.findIndex((e) => e.goods_state == false) == -1)
        this.isfull = true
      else this.isfull = false
    },
    getAmount() {},
    fullChange(val) {
      this.isfull = val
      this.goodslist.forEach((e) => (e.goods_state = this.isfull))
    }
  },
  computed: {
    amount() {
      return this.goodslist
        .filter((e) => e.goods_state)
        .reduce((pre, cur) => pre + cur.goods_price * cur.goods_count, 0)
    },
    total() {
      return this.goodslist
        .filter((e) => e.goods_state)
        .reduce((pre, cur) => pre + cur.goods_count, 0)
    }
  },
  created() {
    this.getGoodList()
  },
  updated() {
    bus.on('changCount', (obj) => {
      this.goodslist[obj.id - 1].goods_count = obj.value
    })
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
